package cn.melonlib.graphql.cores.comp.engine;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.melonlib.graphql.model.metadata.GraphqlFunction;
import cn.melonlib.graphql.model.support.Connection;
import cn.melonlib.graphql.model.support.GraphqlEdge;
import cn.melonlib.graphql.model.support.PageInfo;

import java.util.Collection;


public interface GraphqlDataPackage {

    default Object packageData(Object object, GraphqlFunction graphqlFunction){
        return switch (graphqlFunction.getMode()){
            case QUERY -> switch (graphqlFunction.getQueryMode()){
                case OFFSET -> {
                    Connection connection=new Connection();
                    connection.setTotalCount((Long) ReflectUtil.getFieldValue(object,"total"));
                    connection.setStatus(true);
                    connection.setEdges(((Collection)object).stream().map(GraphqlEdge::new).toList());
                    connection.setPageInfo(new PageInfo(((Long) ReflectUtil.getFieldValue(object,"limit")).intValue(),(Long) ReflectUtil.getFieldValue(object,"offset")));
                    yield connection;
                }
                case PAGINATION -> {
                    Connection connection=new Connection();
                    connection.setTotalCount(BeanUtil.getProperty(object,"total"));
                    connection.setStatus(true);
                    connection.setEdges(((Collection)object).stream().map(GraphqlEdge::new).toList());
                    connection.setPageInfo(new PageInfo(BeanUtil.<Integer>getProperty(object,"page"),BeanUtil.<Integer>getProperty(object,"limit")));
                    yield connection;
                }
                case ONCE -> object;
            };
            case MUTATION -> object;
        };
    }
}
